//
//  XYSegementScrollView.m
//  XYAuto
//
//  Created by 小萌 on 2017/1/3.
//  Copyright © 2017年 Raymond~. All rights reserved.
//

#import "XYSegementScrollView.h"

@interface XYSegementScrollView()
@property (nonatomic, strong) UILabel *lbTopLightGrayLine;//顶部灰色底线

@end
@implementation XYSegementScrollView
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor blackColor];
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.pagingEnabled = NO;
        self.topButtonFont = 16.f;
        self.topButtonMargin = 10.f;
        self.topLineHeight = 3;
        self.seletedIndex = 0;
        self.seletedColor = [UIColor whiteColor];
        self.normalColor = [UIColor colorWithHexString:@"#848484"];
        self.isSegementTitleScale = NO;
        self.segementScale = 0.125;
        self.isAutoLineWidth = NO;
        self.topLineWidth = 50.0f;
        self.isAutoButtonWidth = NO;
        self.isRepeatSeleted = NO;
        self.firstBtnLeftMargin = self.topButtonMargin;
        self.seletedPosition = XYTopSeletedSegementPositionCenter;
        self.btnPosition = XYButtonTitlePositionNomal;
        [self addSubview:self.lbTopLightGrayLine];
//        [self addSubview:self.backImageView];

    }
    return self;
}
- (void)setSegementArray:(NSArray *)segementArray
{
    _segementArray = segementArray;
    [self reloadScrollView];
}
- (UILabel *)lbTopLine
{
    if (!_lbTopLine) {
        _lbTopLine = [[UILabel alloc] init];
    }
    return _lbTopLine;
}
- (void)setCurrentIndex:(NSInteger)currentIndex{
    UIButton *seleted = [self viewWithTag:currentIndex + 500];

    if (seleted) {
        [self clickBtn:seleted];
    }

}
- (UILabel *)lbTopLightGrayLine
{
    if (!_lbTopLightGrayLine) {
        _lbTopLightGrayLine = [[UILabel alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 0.5, self.bounds.size.width, 1)];
        _lbTopLightGrayLine.backgroundColor = [UIColor blackColor];

    }
    return _lbTopLightGrayLine;
}
- (UIImageView *)backImageView
{
    if (!_backImageView) {
        _backImageView = [[UIImageView alloc] initWithFrame:self.bounds];
    }
    return _backImageView;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    self.contentOffset = CGPointMake(self.contentOffset.x, 0);
}
- (void)reloadScrollView
{
    for (UIView *btn in self.subviews) {
        if ([btn isKindOfClass:[XYButton class]]) {
            [btn removeFromSuperview];
        }
    }
    CGFloat topScrollViewContentWidth = 0.0;
    CGFloat btnContentOffX = self.firstBtnLeftMargin;
    for (NSInteger i = 0; i < self.segementArray.count; i ++) {
        XYButton *btn = [XYButton buttonWithType:UIButtonTypeCustom];
        CGSize textSize = [NSString heightForString:self.segementArray[i] Size:CGSizeMake(self.bounds.size.width, self.bounds.size.height) Font:[UIFont systemFontOfSize:self.topButtonFont]].size;
        btn.frame = CGRectMake(btnContentOffX, 0, textSize.width, self.bounds.size.height - self.topLineHeight);
        btn.tag = 500 + i;

        btn.fontFloat = self.topButtonFont;
        btn.titlePosition = self.btnPosition;
        btn.spacing = 0.0f;
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [btn setTitleColor:self.seletedColor forState:UIControlStateSelected];
        [btn setTitleColor:self.normalColor forState:UIControlStateNormal];
        [btn setBackgroundImage:self.normalBackImage forState:UIControlStateNormal];
        [btn setBackgroundImage:self.seletedBackImage forState:UIControlStateSelected];
        [btn setImage:self.normalImage forState:UIControlStateNormal];
        [btn setImage:self.seletedImage forState:UIControlStateSelected];
        [btn setTitle:self.segementArray[i] forState:UIControlStateNormal];
//        btn.titleLabel.font = [UIFont systemFontOfSize:self.topButtonFont];
        [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        if (self.seletedIndex == i) {
            if (self.isAutoLineWidth) {
                self.lbTopLine.size = CGSizeMake(textSize.width, self.topLineHeight);
            }else{
                self.lbTopLine.size = CGSizeMake(self.topLineWidth, self.topLineHeight);
            }
            self.lbTopLine.center = CGPointMake(btn.center.x,self.bounds.size.height - self.topLineHeight * 0.5);
            self.lbTopLine.cornerRadius(self.topLineHeight * 0.5);
            self.lbTopLine.backgroundColor = [UIColor colorWithRed:147/255.0 green:38/255.0 blue:134/255.0 alpha:1.0];;
            btn.selected = YES;
            self.preIndex = i;
            [self addSubview:self.lbTopLine];
            if (self.isSegementTitleScale) {
                btn.transform = CGAffineTransformMakeScale(1 + self.segementScale, 1 + self.segementScale);
            }
        }
        [self addSubview:btn];
        btnContentOffX += (textSize.width + self.topButtonMargin);
        topScrollViewContentWidth += textSize.width;
    }
    topScrollViewContentWidth += (self.topButtonMargin * self.segementArray.count + self.firstBtnLeftMargin);
    
    if (topScrollViewContentWidth < self.bounds.size.width && !self.isAutoButtonWidth) {
            self.topButtonMargin = 0;
            CGFloat width = self.bounds.size.width/self.segementArray.count;
            topScrollViewContentWidth = self.bounds.size.width;
            btnContentOffX = self.topButtonMargin;
            for (NSInteger i = 0; i < self.segementArray.count; i ++) {
                XYButton *btn = [self viewWithTag:500 + i];
                btn.originX = i * width;
                btn.width = width;
                if (self.seletedIndex == i) {
                    if (self.isAutoLineWidth) {
                        self.lbTopLine.width = width;
                    }else{
                        self.lbTopLine.width = self.topLineWidth;
                    }
                    self.lbTopLine.center = CGPointMake(btn.center.x,self.bounds.size.height - self.topLineHeight* 0.5);
                }
        }
    }
    
    self.contentSize = CGSizeMake(topScrollViewContentWidth, self.bounds.size.height);
    self.lbTopLightGrayLine.width = topScrollViewContentWidth;
    if (topScrollViewContentWidth < ScreenWidth) {
        self.contentSize = CGSizeMake(ScreenWidth, self.bounds.size.height);
        self.width = ScreenWidth;
        self.lbTopLightGrayLine.width = ScreenWidth;
    }
    self.lbTopLightGrayLine.originY = self.bounds.size.height - self.lbTopLightGrayLine.height;
    self.backImageView.width = self.width;
}
- (void)clickBtn:(UIButton *)btn
{
    UIButton *seleted = [self viewWithTag:self.seletedIndex + 500];
    if (seleted == btn && !self.isRepeatSeleted) {
        return;
    }
    self.preIndex = seleted.tag - 500;
    self.seletedIndex = btn.tag - 500;
    if (!btn.selected) {
        btn.selected = !btn.selected;
        seleted.selected = NO;
        [UIView animateWithDuration:0.25 animations:^{
            if (self.isAutoLineWidth) {
                self.lbTopLine.width = btn.width;
            }else{
                self.lbTopLine.width = self.topLineWidth;
            }
            self.lbTopLine.center = CGPointMake(btn.center.x,self.bounds.size.height - self.topLineHeight * 0.5);
        }];
        
    }
    if ([self.segementeDelegate respondsToSelector:@selector(didSeletedSegementScrollView:btn:index:)]) {
        [self.segementeDelegate didSeletedSegementScrollView:self btn:[self viewWithTag:500 + self.seletedIndex]  index:self.seletedIndex];
    }

    BlockCallWithThreeArg(self.seletedBlock, self,[self viewWithTag:500 + self.seletedIndex], self.seletedIndex);
    [self adjustScrollViewContentX:btn];
    if (self.isSegementTitleScale) {
        [self selectedTitleBtnColorGradualChangeScrollView:self];
    }
}
- (void)adjustScrollViewContentX:(UIButton *)sender
{
    if (self.seletedPosition == XYTopSeletedSegementPositionCenter) {
        
        // 计算偏移量
        CGFloat offsetX = sender.center.x - self.frame.size.width * 0.5;
        if (offsetX < 0){
            offsetX = 0;
        }
        // 获取最大滚动范围
        CGFloat maxOffsetX = self.contentSize.width - self.frame.size.width;
        
        if (offsetX > maxOffsetX){
            offsetX = maxOffsetX;
        }
        // 滚动标题滚动条
        [self setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    }else{
//        //    //如果 当前显示的最后一个tab文字超出右边界
        if (sender.originX - self.contentOffset.x > self.bounds.size.width - (self.topButtonMargin+sender.bounds.size.width) ) {
            //向左滚动视图，显示完整tab文字
            [self setContentOffset:CGPointMake(sender.frame.origin.x - (self.bounds.size.width- (self.topButtonMargin+sender.bounds.size.width)), 0)  animated:YES];
        }
        //如果 当前显示的最后一个tab文字超出右边界
        //如果 （tab的文字坐标 - 当前滚动视图左边界所在整个视图的x坐标） < 按钮的隔间 ，代表tab文字已超出边界
        if (sender.frame.origin.x - self.contentOffset.x < self.topButtonMargin) {
            //向右滚动视图（tab文字的x坐标 - 按钮间隔 = 新的滚动视图左边界在整个视图的x坐标），使文字显示完整
            [self  setContentOffset:CGPointMake(sender.frame.origin.x - self.topButtonMargin, 0)  animated:YES];
        }
        
    }
    
}

/**缩放效果的实现 */
- (void)selectedTitleBtnColorGradualChangeScrollView:(UIScrollView *)scrollView {
    
    if (scrollView == self) {
        UIButton *preBtn = [self viewWithTag:500 + self.preIndex];
        UIButton *seltedBtn = [self viewWithTag:500 + self.seletedIndex];
        if (self.isSegementTitleScale) {
            [UIView animateWithDuration:0.2 animations:^{
                preBtn.transform = CGAffineTransformMakeScale(1,1);
                seltedBtn.transform = CGAffineTransformMakeScale(self.segementScale + 1, self.segementScale + 1);
            }];
        }
    }else{
        CGFloat curPage = scrollView.contentOffset.x / self.bounds.size.width;
        // 左边button角标
        NSInteger leftIndex = curPage;
        // 右边的button角标
        NSInteger rightIndex = leftIndex + 1;
        // 获取左边的button
        UIButton *leftBtn = [self viewWithTag:500 + leftIndex];
        // 获取右边的button
        UIButton *rightBtn;
        if (rightIndex < self.segementArray.count) {
            rightBtn = [self viewWithTag:500 + rightIndex];
        }
        // 计算下右边缩放比例
        CGFloat rightScale = curPage - leftIndex;
        
        // 计算下左边缩放比例
        CGFloat leftScale = 1 - rightScale;
        if (self.isSegementTitleScale) {
//            // 左边缩放
            leftBtn.transform = CGAffineTransformMakeScale(leftScale * self.segementScale + 1, leftScale * self.segementScale + 1);
            // 右边缩放
            rightBtn.transform = CGAffineTransformMakeScale(rightScale * self.segementScale + 1, rightScale * self.segementScale + 1);

        }
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
